package com.tiantong.aibilian;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.mt.mtloadingmanager.LoadingDialog;
import com.mt.mtloadingmanager.LoadingManager;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tiantong.aibilian.R;
import com.tiantong.aibilian.config.API;
import com.tiantong.aibilian.config.HexConvert;
import com.tiantong.aibilian.model.MyData;

import org.apache.log4j.chainsaw.Main;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import adapter.BleAdapter;
import adapter.DataAdapter;
import util.ByteUtil;
import util.CRC;
import util.ExcelUtil;
import util.HexUtil;
import util.HttpClient;
import util.SQLiteHelper;

import static android.bluetooth.BluetoothDevice.TRANSPORT_LE;

public class MainActivity extends Activity {

    private static final String TAG = "ble_tag";
    ProgressBar pbSearchBle;
    ImageView ivSerBleStatus;
    TextView tvSerBleStatus;
    TextView tvSerBindStatus;
    ListView bleListView;

    private LinearLayout myview;


    private List<BluetoothDevice> mDatas;
    private List<Integer> mRssis;
    private BleAdapter mAdapter;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothManager mBluetoothManager;
    private boolean isScaning = false;
    private boolean isConnecting = false;
    private BluetoothGatt mBluetoothGatt;

    //服务和特征值
    private UUID write_UUID_service;
    private UUID write_UUID_chara;
    private UUID read_UUID_service;
    private UUID read_UUID_chara;
    private UUID notify_UUID_service;
    private UUID notify_UUID_chara;
    private UUID indicate_UUID_service;
    private UUID indicate_UUID_chara;


    private ListView mybox;
    private String uuid = "0000fff0-0000-1000-8000-00805f9b34fb";
    private String readuuid = "0000fff1-0000-1000-8000-00805f9b34fb";
    private String writeuuid = "0000fff2-0000-1000-8000-00805f9b34fb";
    private StringBuffer sb = new StringBuffer();
    private String filePaths = "";

    private List<String> Columns = new ArrayList<>();
    private List<String[]> body = new ArrayList<>();
    private LoadingManager loadingManager;
    private Date mydate;
    private String url="";

    private SQLiteHelper db ;

    private TextView txthr,txtbr,txtstate,txttime,txttidong,txtqita;
    private Button btndaochu,btnclear,btndel;

    private  ListView listView;
    private DataAdapter dataAdapter;
    List<MyData> myDataList;

    private SQLiteHelper sqLiteHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_device);



//        String str ="5a 01 12 0a 0a 0a 00 0c 00 00 10 02 00 00 02 02 14 02 02 00 02 02 00 02 04 00 00 01 02 04 00 12 02 04 02 14 10 01 02 02 0a 06 14 15 0f 01 04 00 04 02 02 16 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  cae8";
//        str =str.replace(" ","");
//
//
//        String xinlvstr = str.substring(16,16+(60*2));
//        String huxistr = str.substring(16+(60*2),16+(80*2));
//
//        List<Integer> xinlvarr = HexConvert.getarr(xinlvstr,2);
//        List<Integer> huxiarr = HexConvert.getarr(huxistr,2);

        //  0b 01 15 0b 00 0d 00 24 00 e41a

      //  String str ="0b01150b000d002400e41a";

//        byte[] bytes1 = HexConvert.hexStringToBytes(str.substring(6,10));
//
//        final int xinlvbianyixing1 =   getShort_1(bytes1,0);

                //getShort_1(str.substring(6,8).getBytes(),0);

        initView();
        initData();
        checkPermissions();
        mBluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, 0);
        }

    }
    public  String ReadDayDayString(Context context) {

        InputStream is = null;

        String msg = null;

        try {

            is = context.getResources().getAssets().open("mprespons.txt");

            byte[] bytes = new byte[is.available()];

            is.read(bytes);

            msg = new String(bytes);

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            try {

                is.close();

            } catch (IOException e) {

                e.printStackTrace();

            }
        }
        return  msg;
    }


    private void initData() {
        mDatas = new ArrayList<>();
        mRssis = new ArrayList<>();
        mAdapter = new BleAdapter(MainActivity.this, mDatas, mRssis);
        bleListView.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();

        myDataList =new ArrayList<>();
        dataAdapter = new DataAdapter(MainActivity.this,myDataList);
        listView.setAdapter(dataAdapter);
        dataAdapter.notifyDataSetChanged();


    }

    private void initView() {
        pbSearchBle = findViewById(R.id.progress_ser_bluetooth);
        ivSerBleStatus = findViewById(R.id.iv_ser_ble_status);
        tvSerBindStatus = findViewById(R.id.tv_ser_bind_status);
        tvSerBleStatus = findViewById(R.id.tv_ser_ble_status);
        bleListView = findViewById(R.id.ble_list_view);
        txthr =findViewById(R.id.txthr);
        txtbr = findViewById(R.id.txtbr);
        txtstate= findViewById(R.id.txtstate);
        myview = findViewById(R.id.myview);
        txttidong=findViewById(R.id.txttidong);
        txttime=findViewById(R.id.txttime);
        listView =findViewById(R.id.lvdata);
        txtqita= findViewById(R.id.txtqita);

        sqLiteHelper= new SQLiteHelper(this);
        btndaochu =findViewById(R.id.btndaochu);
        btnclear = findViewById(R.id.btnclear);
        btndel = findViewById(R.id.btndel);


//
        loadingManager = new LoadingManager(this);


        btndaochu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String excelFileName = "/设备数据" + System.currentTimeMillis() + ".xls";
                String sheetName = "demoSheetName";

                File file = new File(MainActivity.this.getExternalFilesDir(null).getPath() + "/" + excelFileName);

                filePaths = file.getPath();
                body = new ArrayList<>();
                Columns= new ArrayList<>();

                Columns.add("类型");
                Columns.add("值");
                Columns.add("时间");

                Cursor cursor=  sqLiteHelper.selectsql("select * from work");
                StringBuffer sb = new StringBuffer();
                sb.append("类型,值,时间"+"\r\n");
                while (cursor.moveToNext()) {

                    String[] items =new String[3];
                    items[0]= cursor.getString(cursor
                            .getColumnIndex("type"));
                    items[1]= cursor.getString(cursor
                            .getColumnIndex("value"));
                    items[2]= cursor.getString(cursor
                            .getColumnIndex("time"));
                    body.add(items);

                    sb.append(items[0]+","+items[1]+","+items[2]+"\r\n");
                }


                API.writeContent(MainActivity.this,"test.csv",sb.toString());
                Toast.makeText(MainActivity.this,body.size()+"",Toast.LENGTH_SHORT).show();
              //  ExcelUtil.initExcel(filePaths, sheetName, Columns);
              //  ExcelUtil.writeObjListToExcel(body, filePaths, MainActivity.this);


                openFileByApp(getApplicationContext(), new File(MainActivity.this.getExternalFilesDir(null).getPath()+"/"+"test.csv"));
             //   HttpClient.uploadFile("https://mall.tiantong369.com/upload/file",file,mHandler,2);


            }
        });


        btnclear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myDataList.clear();
                dataAdapter.notifyDataSetChanged();
                Toast.makeText(MainActivity.this,"操作成功",Toast.LENGTH_SHORT).show();
            }
        });

        btndel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                sqLiteHelper.deleteAll();
                Toast.makeText(MainActivity.this,"操作成功",Toast.LENGTH_SHORT).show();

            }
        });

        db = new SQLiteHelper(this);
        ivSerBleStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isScaning) {
                    tvSerBindStatus.setText("停止搜索");
                    stopScanDevice();
                } else {
                    scanDevice();
                    //  checkPermissions();
                }

            }
        });
        bleListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                if (isScaning){
//                    stopScanDevice();
//                }
                if (!isConnecting) {
                    isConnecting = true;
                    BluetoothDevice bluetoothDevice = mDatas.get(position);
                    //连接设备
                    tvSerBindStatus.setText("连接中");
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        mBluetoothGatt = bluetoothDevice.connectGatt(MainActivity.this,
                                true, gattCallback, TRANSPORT_LE);
                    } else {
                        mBluetoothGatt = bluetoothDevice.connectGatt(MainActivity.this,
                                true, gattCallback);
                    }
                }

            }
        });


    }


    private void readData() {
        BluetoothGattCharacteristic characteristic = mBluetoothGatt.getService(read_UUID_service)
                .getCharacteristic(read_UUID_chara);
        mBluetoothGatt.readCharacteristic(characteristic);

        mBluetoothGatt.setCharacteristicNotification(characteristic, true);
    }


    /**
     * 开始扫描 10秒后自动停止
     */
    private void scanDevice() {
        tvSerBindStatus.setText("正在搜索");
        isScaning = true;
        pbSearchBle.setVisibility(View.VISIBLE);
        mBluetoothAdapter.startLeScan(scanCallback);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //结束扫描
                mBluetoothAdapter.stopLeScan(scanCallback);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        isScaning = false;
                        pbSearchBle.setVisibility(View.GONE);
                        tvSerBindStatus.setText("搜索已结束");
                    }
                });
            }
        }, 100000);
    }

    /**
     * 停止扫描
     */
    private void stopScanDevice() {
        isScaning = false;
        pbSearchBle.setVisibility(View.GONE);
        mBluetoothAdapter.stopLeScan(scanCallback);
    }
    public static int getInt_1(byte[] bytes,int index){
        int value=(int)((bytes[index]&0xff)
                |(bytes[index+1]<<8&0xff00)
                |(bytes[index+2]<<16&0xff0000)
                |(bytes[index+3]<<24&0xff000000));
        return value;
    }
    public static short getShort_1(byte[] bytes,int index){
        return (short)(
                (bytes[index]&0xff)
                        |(bytes[index+1]<<8&0xff00)
        );
    }
    BluetoothAdapter.LeScanCallback scanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
           // Log.e(TAG, "run: scanning...");
            String name = device.getName();

            if (name != null) {

                if (!mDatas.contains(device) ) {
                    mDatas.add(device);
                    mRssis.add(rssi);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mAdapter.notifyDataSetChanged();
                        }
                    });



                }

            }


        }
    };

    private BluetoothGattCallback gattCallback = new BluetoothGattCallback() {


        /**
         * 断开或连接 状态发生变化时调用
         * */
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            Log.e(TAG, "onConnectionStateChange()");
            if (status == BluetoothGatt.GATT_SUCCESS) {
                //连接成功
                if (newState == BluetoothGatt.STATE_CONNECTED) {
                    Log.e(TAG, "连接成功");
                    //发现服务
                    gatt.discoverServices();
                }
            } else {
                //连接失败
                Log.e(TAG, "失败==" + status);
                mBluetoothGatt.close();
                isConnecting = false;
            }
        }

        /**
         * 发现设备（真正建立连接）
         * */
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
            //直到这里才是真正建立了可通信的连接
            isConnecting = false;
            Log.e(TAG, "onServicesDiscovered()---建立连接");
            //获取初始化服务和特征值
            initServiceAndChara();
            //订阅通知


            BluetoothGattService bluetoothGattService = mBluetoothGatt.getService(UUID.fromString(uuid));

            BluetoothGattCharacteristic notifyCharacteristic = bluetoothGattService.getCharacteristic(UUID.fromString(readuuid));

//            boolean isEnableNotification = gatt.setCharacteristicNotification(notifyCharacteristic, true);
//            System.out.println("isEnableNotification" + isEnableNotification);


            BluetoothGattCharacteristic characteristic=mBluetoothGatt
                    .getService(notify_UUID_service).getCharacteristic(notify_UUID_chara);
            boolean isEnableNotification =  mBluetoothGatt.setCharacteristicNotification(characteristic,true);
            System.out.println("isEnableNotification"+isEnableNotification);


            if(isEnableNotification) {
                List<BluetoothGattDescriptor> descriptorList = characteristic.getDescriptors();
                if(descriptorList != null && descriptorList.size() > 0) {
                    for(BluetoothGattDescriptor descriptor : descriptorList) {
                        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                        mBluetoothGatt.writeDescriptor(descriptor);
                    }
                }
            }


            try {
                Thread.sleep(150);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    bleListView.setVisibility(View.GONE);
                    myview.setVisibility(View.VISIBLE);

                    tvSerBindStatus.setText("已连接");
                    //  stopScanDevice();
                }
            });
        }


        /**
         * 读操作的回调
         * */
        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);

            final byte[] data = characteristic.getValue();
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    addText(tvResponse,bytes2hex(data));
//                }
//            });
            Log.e(TAG, "onCharacteristicRead()" + HexUtil.encodeHexStr(characteristic.getValue()));
        }

        /**
         * 写操作的回调
         * */
        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicWrite(gatt, characteristic, status);

            String str = HexUtil.encodeHexStr(characteristic.getValue());
            Log.e(TAG, "onCharacteristicWrite()  status=" + status + ",value=" + HexUtil.encodeHexStr(characteristic.getValue()));

        }

        /**
         * 接收到硬件返回的数据
         * */
        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
     //       Log.e(TAG, "onCharacteristicChanged()" + characteristic.getValue());
            final byte[] data = characteristic.getValue();




            try{
                if(data.length>0){
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    final String time = df.format(new Date());

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            txttime.setText("更新时间："+ formatter.format(new Date()));
                        }
                    });


                    List<String> arr = new ArrayList<>();
                    String str = ByteUtil.bytes2hex(data);
                 //   Log.e(TAG, "数据"+str);


                    List<String> items = hextoList(str,arr);
                    for(int i=0;i< items.size();i++){

                        String item = items.get(i);
                        //07 01 11 4a 15 3696
                        String command = item.substring(4,6);
                        Log.e(TAG, "command:"+command);
                        Log.e(TAG, "数据:"+item);
                        if(command.equals("13")){
                            //异步在床离床数据,
                            String code = item.substring(2,4);
                            String statehex = item.substring(6,8);
                            String state="";
                            if(Integer.parseInt(statehex,16)==1){
                                state="1";
                            }else{
                                state="0";
                            }
                            final String finalState = state;

                            JSONObject jsonObject = new JSONObject();

                                jsonObject.put("type",13);
                                jsonObject.put("code",code);
                                jsonObject.put("state",state);


                                MyData myData = new MyData();
                                myData.setType("在床离床");
                                myData.setValue(state);
                                myData.setTime(time);
                           //     myDataList.add(myData);

                                 sqLiteHelper.insert("在床离床",state,time);

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        txtstate.setText("状态："+ finalState);
                                       // dataAdapter.notifyDataSetChanged();
                                    }
                                });


                        }else if(command.equals("11")){
                            //期性高频体征数据
                            final String code = item.substring(2,4);
                            final String hr = item.substring(6,8);
                            final String br = item.substring(8,10);
                            Integer hrInt = Integer.parseInt(hr,16);
                            Integer brInt = Integer.parseInt(br,16);
                            Log.e(TAG, "hr:"+hrInt);
                            Log.e(TAG, "br:"+brInt);

                            JSONObject jsonObject = new JSONObject();

                                jsonObject.put("type",11);
                                jsonObject.put("hr",hrInt);
                                jsonObject.put("br",brInt);
                                jsonObject.put("code",code);


                                MyData myData1 = new MyData();
                                myData1.setType("心率");
                                myData1.setValue(hrInt+"");
                                myData1.setTime(time);
                              //  myDataList.add(myData1);
                                sqLiteHelper.insert("心率",hrInt+"",time);

                                MyData myData2 = new MyData();
                                myData2.setType("呼吸");
                                myData2.setValue(brInt+"");
                                myData2.setTime(time);
                               // myDataList.add(myData2);
                                sqLiteHelper.insert("呼吸",brInt+"",time);

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                //    dataAdapter.notifyDataSetChanged();
                                    txthr.setText("心率："+Integer.parseInt(hr,16));
                                    txtbr.setText("呼吸："+Integer.parseInt(br,16));
                                }
                            });
                        }else if(command.equals("12")){
                            //周期性低频体征数据
                            String code = item.substring(2,4);
                            int dianya =  Integer.parseInt(item.substring(6,8),16);
                            int anjing =  Integer.parseInt(item.substring(8,10),16);
                            int dahan =  Integer.parseInt(item.substring(10,12),16);
                            final int huxixiaoyu1 =  Integer.parseInt(item.substring(12,14),16);
                            final int huxixiaoyu2 =  Integer.parseInt(item.substring(14,16),16);
                            final int huxixiaoyu3 =  Integer.parseInt(item.substring(16,18),16);
                            final int huxixiaoyu4 =  Integer.parseInt(item.substring(18,20),16);


                            sqLiteHelper.insert("呼吸小于1",huxixiaoyu1+"",time);
                            sqLiteHelper.insert("呼吸小于2",huxixiaoyu2+"",time);
                            sqLiteHelper.insert("呼吸小于3",huxixiaoyu3+"",time);
                            sqLiteHelper.insert("呼吸小于4",huxixiaoyu4+"",time);


                            String xinlvstr = item.substring(20,20+(60*2));
                            String huxistr = item.substring(20+(60*2),20+(80*2));

                            List<Integer> xinlvarr = HexConvert.getarr(xinlvstr,2);
                            List<Integer> huxiarr = HexConvert.getarr(huxistr,2);



                            for(int n=0;n<xinlvarr.size();n++){
                                sqLiteHelper.insert("心率变异性",(xinlvarr.get(n)*10)+"",time);
                            }
                            for(int n=0;n<huxiarr.size();n++){
                                sqLiteHelper.insert("呼吸变异性",(huxiarr.get(n)*10)+"",time);
                            }
                            sqLiteHelper.insert("安静系数",anjing+"",time);
                            sqLiteHelper.insert("打鼾",dahan+"",time);


                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        txtqita.setText("呼吸小于:"+huxixiaoyu1+","+huxixiaoyu2+","+huxixiaoyu3+","+huxixiaoyu4+",更新时间"+time);
                                    }
                                });




                        }else if(command.equals("14")){
                            //异步体动数据
                            final int statehex =  Integer.parseInt(item.substring(6,8),16);
                            String code = item.substring(2,4);
                            JSONObject jsonObject = new JSONObject();

                                jsonObject.put("type",14);
                                jsonObject.put("code",code);
                                jsonObject.put("state",statehex);

                                MyData myData1 = new MyData();
                                myData1.setType("体动");
                                myData1.setValue(statehex+"");
                                myData1.setTime(time);
                             //   myDataList.add(myData1);
                                sqLiteHelper.insert("体动",statehex+"",time);


                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                               //         dataAdapter.notifyDataSetChanged();

                                        txttidong.setText("体动："+statehex);

                                    }
                                });


                        }else if(command.equals("15")){
                            //异步体动数据
                          //  0b 01 15 0b 00 0d 00 24 00 e41a




                            byte[] bytes1 = HexConvert.hexStringToBytes(item.substring(6,10));
                            byte[] bytes2 = HexConvert.hexStringToBytes(item.substring(10,14));
                            byte[] bytes3 = HexConvert.hexStringToBytes(item.substring(14,18));



                            final int xinlvbianyixing1 = getShort_1(bytes1,0);
                            final int xinlvbianyixing2 =  getShort_1(bytes2,0);
                            final int xinlvbianyixing3 =   getShort_1(bytes3,0);




                            MyData myData1 = new MyData();
                            myData1.setType("心率变异性低于50");
                            myData1.setValue(xinlvbianyixing1+"");
                            myData1.setTime(time);
                          //  myDataList.add(myData1);
                            sqLiteHelper.insert("心率变异性低于50",xinlvbianyixing1+"",time);



                            MyData myData2 = new MyData();
                            myData2.setType("心率变异性低于100");
                            myData2.setValue(xinlvbianyixing2+"");
                            myData2.setTime(time);
                        //    myDataList.add(myData2);
                            sqLiteHelper.insert("心率变异性低于100",xinlvbianyixing2+"",time);


                            MyData myData3 = new MyData();
                            myData3.setType("心率变异性高于100");
                            myData3.setValue(xinlvbianyixing3+"");
                            myData3.setTime(time);
                         //   myDataList.add(myData3);
                            sqLiteHelper.insert("心率变异性高于100",xinlvbianyixing3+"",time);


                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                 //   dataAdapter.notifyDataSetChanged();


                                }
                            });


                        }
                    }
                }


            }catch (Exception e){


            }


        }
    };

    private static List<String> hextoList(String str,List<String> list){

        if(!str.isEmpty()){

            int len = Integer.parseInt(str.substring(0,2),16) *2;
            list.add(str.substring(0,len));

            hextoList(str.substring(len,str.length()),list);
        }

        return list;

    }

    private  void openFileByApp(Context context, File f) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(f).toString());
            String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension("xls");



            //7.0以上需要
            if (Build.VERSION.SDK_INT >= 24) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Uri uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", f);
                intent.setDataAndType(uri, mimetype);
            } else {

                intent.setDataAndType(Uri.fromFile(f), mimetype);
            }


            startActivity(intent);

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(context, "打开文件出错，无支持的应用", Toast.LENGTH_LONG).show();

        }
    }

    private Handler mHandler = new Handler() {

        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    String str = sb.toString();




                    loadingManager.hideSuccess("数据获取成功！", new LoadingDialog.OnDialogDismissedListener() {
                        @Override
                        public void onDialogDismissed() {

                        }
                    });

                    break;
                case 2:
                    //{"code":200,"message":"上传成功","pic":"https://mall.tiantong369.com//uploads/20220728/1658973470123-imgFile","file":"/uploads/20220728/1658973470123-imgFile"}
                    try {
                        JSONObject json = new JSONObject(msg.obj.toString());
                        String code = json.getString("code");

                        if (!code.equals("200")) {
                            String message = json.getString("message");
                            Toast.makeText(getApplicationContext(),
                                    message, Toast.LENGTH_SHORT)
                                    .show();

                        } else {
                            url=json.getString("pic");
                            Toast.makeText(MainActivity.this, "导出数据成功", Toast.LENGTH_SHORT).show();
                            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
// 创建普通字符型ClipData
                            ClipData  mClipData = ClipData.newPlainText("Label", url);
// 将ClipData内容放到系统剪贴板里。
                            cm.setPrimaryClip(mClipData);


                        }
                    }catch (Exception ee){

                    }


                    break;
            }
        }
    };


    private void checkPermissions() {
        RxPermissions rxPermissions = new RxPermissions(MainActivity.this);
        rxPermissions.request(android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        )
                .subscribe(new io.reactivex.functions.Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            // 用户已经同意该权限

                            Toast.makeText(MainActivity.this, "授权成功", Toast.LENGTH_SHORT).show();
                        } else {
                            // 用户拒绝了该权限，并且选中『不再询问』
                            //  ToastUtils.showLong("用户开启权限后才能使用");
                            Toast.makeText(MainActivity.this, "拒绝授权将无法使用", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }


    private void initServiceAndChara() {
        List<BluetoothGattService> bluetoothGattServices = mBluetoothGatt.getServices();
        for (BluetoothGattService bluetoothGattService : bluetoothGattServices) {

            //String uuid = "00001800-0000-1000-8000-00805f9b34fb";
            if (bluetoothGattService.getUuid().toString().toUpperCase().equals(uuid.toUpperCase())) {

                List<BluetoothGattCharacteristic> characteristics = bluetoothGattService.getCharacteristics();
                for (BluetoothGattCharacteristic characteristic : characteristics) {
                    int charaProp = characteristic.getProperties();
                    if ((charaProp & BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
                        read_UUID_chara = characteristic.getUuid();
                        read_UUID_service = bluetoothGattService.getUuid();
                        Log.e(TAG, "read_chara=" + read_UUID_chara + "----read_service=" + read_UUID_service);
                    }
                    if ((charaProp & BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) {
                        write_UUID_chara = characteristic.getUuid();
                        write_UUID_service = bluetoothGattService.getUuid();
                        Log.e(TAG, "write_chara=" + write_UUID_chara + "----write_service=" + write_UUID_service);
                    }
                    if ((charaProp & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) > 0) {
                        write_UUID_chara = characteristic.getUuid();
                        write_UUID_service = bluetoothGattService.getUuid();
                        Log.e(TAG, "write_chara=" + write_UUID_chara + "----write_service=" + write_UUID_service);

                    }
                    if ((charaProp & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                        notify_UUID_chara = characteristic.getUuid();
                        notify_UUID_service = bluetoothGattService.getUuid();
                        Log.e(TAG, "notify_chara=" + notify_UUID_chara + "----notify_service=" + notify_UUID_service);
                    }
                    if ((charaProp & BluetoothGattCharacteristic.PROPERTY_INDICATE) > 0) {
                        indicate_UUID_chara = characteristic.getUuid();
                        indicate_UUID_service = bluetoothGattService.getUuid();
                        Log.e(TAG, "indicate_chara=" + indicate_UUID_chara + "----indicate_service=" + indicate_UUID_service);

                    }
                }

            }


        }
    }

    private void addText(TextView textView, String content) {
        textView.append(content);
        textView.append("\n");
        int offset = textView.getLineCount() * textView.getLineHeight();
        if (offset > textView.getHeight()) {
            textView.scrollTo(0, offset - textView.getHeight());
        }
    }

    private void writeData(String content) {


    }





    @Override
    protected void onDestroy() {
        super.onDestroy();
        mBluetoothGatt.disconnect();
    }
}
